package com.O1DesignModel;

import java.util.ArrayList;
import java.util.List;

/**
 * 模式定义：定义对象间的一种一对多依赖关系，当一个对象状态改变时，其依赖的对象都能得到通知并自动更新。
 * 适用场景：
 *
 * 消息订阅与发布（如事件总线、通知系统）。
 * 监听状态变化（如股票价格变动、天气预警）。
 */
interface Observer {
    void addObserver(WeatherObserver observer);
    void removeObserver(WeatherObserver observer);
    void notifyObservers();
    void setTemperature(float temperature);
}
interface  WeatherObserver{
    void update(float temperature);
}

class WeatherStation implements Observer {
    List<WeatherObserver> weatherObserverList = new ArrayList<>();
    private float temperature;
    @Override
    public void addObserver(WeatherObserver observer) {
        weatherObserverList.add(observer);
    }

    @Override
    public void removeObserver(WeatherObserver observer) {
        weatherObserverList.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (WeatherObserver weatherObserver : weatherObserverList) {
            weatherObserver.update(temperature);
        }
    }

    @Override
    public void setTemperature(float temperature) {
        this.temperature = temperature;
        notifyObservers();
    }
}

class MobileObserver implements WeatherObserver {
    private String name;
    public MobileObserver(String name){
        this.name = name;
    }
    @Override
    public void update(float temperature) {
        System.out.println(name + "收到温度变化通知，温度为：" + temperature);
    }
}

public class O3_Observer {
    public static void main(String[] args) {
        MobileObserver gdWeather = new MobileObserver("高德地图天气");
        MobileObserver txWeather = new MobileObserver("腾讯天气");

        WeatherStation weatherStation = new WeatherStation();
        weatherStation.addObserver(gdWeather);
        weatherStation.addObserver(txWeather);
        weatherStation.setTemperature(25.0f);

    }
}
